package com.chy.common;

import com.alibaba.fastjson.JSON;
import com.chy.common.BaseContext;
import com.chy.common.JacksonObjectMapper;
import com.chy.common.R;
import com.chy.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;

@Component
@Slf4j
public class ProjectIntercepter implements HandlerInterceptor {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        // 定义不需要处理的请求路径
        String[] urls = new String[]{
                "/user/getUserInfo",
                "/user/getUser",
                "/user/login",
                "/user/register",
                "/user/logout",
                "/common/upload/file",
                "/common/upload/img",
                "/common/upload/video",
                "/common/download/file",
                "/common/download/img",
                "/common/download/video",
                "/category/allList",
                "/article/list",
                "/article/getArtById",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/menu/getRouter",
                "/menu/addRouter",
                "/chat/add",
                "/chat/status",
                "/chat/status2",

        };
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            return true;
        }
        String Authorization = request.getHeader("Authorization");
        if(Authorization != null && !Authorization.isEmpty()) {
            Claims jwt = JwtUtil.verifyJwt(Authorization.replace("Bearer ", ""));
            HashMap<String, Object> jwtMap = Utils.ObjectToMap(jwt);
            System.out.println(jwtMap);

            if(Long.parseLong(String.valueOf(jwtMap.get("exp"))) * 1000 < System.currentTimeMillis()) {
                // 登录过期
                handleResult(R.loginExpire(), response);
            }

            if(Boolean.TRUE.equals(redisTemplate.hasKey(jwtMap.get("id")))){
//                String token = redisTemplate.boundValueOps(jwtMap.get("id")).get().toString();
//                Claims verifyJwt = JwtUtil.verifyJwt(token);
//                HashMap redisJwt = Utils.ObjectToMap(verifyJwt);
//                System.out.println(redisJwt);
                return true;
            }else {
                // 登录过期
                handleResult(R.loginExpire(), response);
            }
        }


//        if(request.getSession().getAttribute("user") != null){
//            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
//            Long userId = (Long) request.getSession().getAttribute("user");
//            BaseContext.setCurrentId(userId);
//            return true;
//        }

        log.info("用户未登录");
        handleResult(R.noLogin(), response);

        return false;
    }

    private static void handleResult(R<User> objectR ,HttpServletResponse response) throws IOException {
//        R<User> objectR = R.noLogin();
        //将result对象转为json串
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(JSON.toJSONString(objectR));
        writer.flush();
        writer.close();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
